package com.ynu.springbootappdemo.controller;

import com.ynu.springbootappdemo.common.utils.BaseResponse;
import com.ynu.springbootappdemo.common.utils.ResultUtils;
import com.ynu.springbootappdemo.model.dto.cart.SaveCartDTO;
import com.ynu.springbootappdemo.model.entity.Cart;
import com.ynu.springbootappdemo.model.entity.Properties;
import com.ynu.springbootappdemo.model.entity.SkuItem;
import com.ynu.springbootappdemo.model.vo.CartVo;
import com.ynu.springbootappdemo.model.vo.SkuItemVo;
import com.ynu.springbootappdemo.service.CartService;
import com.ynu.springbootappdemo.service.GoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.modelmapper.ModelMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "购物车")
@RestController
@RequestMapping("/cart")
public class CartController {

    @Resource
    private CartService service;

    @Resource
    private GoodsService goodsService;
    @Resource
    private ModelMapper modelMapper;

    @GetMapping("/getAll")
    @ApiOperation("获取所有购物车")
    @Transactional
    public BaseResponse<List<CartVo>> getAll(HttpServletRequest request){
        List<Cart> carts = service.getAll(request);

        List<CartVo> cartVos = new ArrayList<>();

        carts.forEach(cart -> {
            CartVo cartVo = modelMapper.map(cart, CartVo.class);
            SkuItem skuItem = cart.getSkuItem();

            List<Properties> properties = goodsService.parserProp(skuItem.getItemSpec());

            SkuItemVo itemVo = modelMapper.map(skuItem, SkuItemVo.class);

            itemVo.setItemSpec(properties);
            cartVo.setSkuItemVo(itemVo);
            cartVos.add(cartVo);
        });

        return ResultUtils.success(cartVos);
    }

    @PostMapping("/save")
    @ApiOperation("保存购物车")
    @Transactional
    public BaseResponse<CartVo> save(@ApiParam("商品数据") @RequestBody SaveCartDTO dto, HttpServletRequest request){
        Cart cart = service.saveCart(dto, request);

        CartVo cartVo = modelMapper.map(cart, CartVo.class);
        SkuItem skuItem = cart.getSkuItem();

        List<Properties> properties = goodsService.parserProp(skuItem.getItemSpec());
        SkuItemVo itemVo = modelMapper.map(skuItem, SkuItemVo.class);
        itemVo.setItemSpec(properties);
        cartVo.setSkuItemVo(itemVo);

        return ResultUtils.success(cartVo);
    }
}
